package voicecall.shb.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by dyh on 2019/1/29.
 */
public class EchoServer {
    private int port;

    public EchoServer(int port){
        this.port = port;
    }

    /**
     * ��������
     */
    public void run() throws InterruptedException {
        //�߳���
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<io.netty.channel.socket.SocketChannel>() {

                        @Override
                        protected void initChannel(io.netty.channel.socket.SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new EchoServerHandler());
                        }
                    });

            String sPrint = "Echo服务器启动ing";
//            try {
//                System.out.print(new String(sPrint.getBytes("utf-8"),"gbk"));
//            }catch (Exception e){
//
//            }

            //�󶨶˿ڣ�ͬ���ȴ��ɹ�
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            //�ȴ�����˿ڹر�
            channelFuture.channel().closeFuture().sync();
        }finally {

            //�����˳�
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }

    public static void main(String [] args) throws InterruptedException {
        int port = 8080;
        if (args.length>0){
            port = Integer.parseInt(args[0]);
        }

        new EchoServer(port).run();
    }
}
